//主题赛 结算逻辑
const log = require("../../utils/log");
const CmdZt = require("../proto/CmdZt");
const gameZtCfg = require("./gameZtCfg");
const AlgorZt = require("./algorZt");
const {RewardType} = require("../../config/gameCfg");
const redisBase = require("../../common/RedisBase");

class GameZtEnd {
    static getInstance() {
        if (!GameZtEnd.instance) {
            GameZtEnd.instance = new GameZtEnd();
            return GameZtEnd.instance;
        } else {
            return GameZtEnd.instance;
        }
    }

    //广播结算
    async broadGammEndCur(uid, gameType,roomInfo,roomId,client,session){
        log.info("=========广播当前5道题目答完结算=========")
        let ret = {
            type: CmdZt.ThemeMatchGameEndBroadcast,
            data:{
                users:[],
            }
        }

        let users = roomInfo.users;
        for (const key in users) {
            let cfg = users[key];
            log.info("=========广播当前5道题目答完结算=========",key)
            let user = await global.gameSerMgr.gameRedis.get_redes_in_gameInfo_list_zt_info(key,gameType);
            let item = {
                userId: user.uid,
                name : user.name,
                avator : user.avator,
                score : cfg.totalScore,
                time : cfg.totalTime,
            }

            ret.data.users.push(item);
        }
        log.info("=========广播当前5道题目答完结算======2222===")
        //判断输赢跟新勋章数量
        let uids = Object.keys(users);
        if(users[uids[0]].totalScore > users[uids[1]].totalScore){
            users[uids[0]].isWin = 1;
            users[uids[1]].isWin = 0;
        }else{
            users[uids[0]].isWin = 0;
            users[uids[1]].isWin = 1;
        }

        log.info("=======广播当前轮结算=======");

        setTimeout(()=>{
            log.info("======当前轮结算============")
            for (let i = 0; i < session.length; i++) {
                let cfg = session[i];
                let client = cfg.client;
                client.send(JSON.stringify(ret));
            }
            log.info("======广播当前轮结算 end============")
        },1200)



        log.info("=======晋级结算=======");
        setTimeout(async ()=>{
            //晋级结算判断
            for (const key in users) {
                let user = users[key];
                await this.updateUserXZAndLv(key,gameType,user.isWin,session);
            }
        },1300)
    }

    //检测段位结算
    async updateUserXZAndLv(uid,gameType,isWin,session){
        log.info('=======updateUserXZAndLv============',uid,gameType,isWin);
        let gameInfoList = await redisBase.getGameListZt();
        if(gameInfoList){
            log.info('========updateUserXZAndLv=========',gameInfoList.length);
            for (let i = 0; i < gameInfoList.length; i++) {
                log.info('===========updateUserScore ==============',i);
                let cfg = JSON.parse(gameInfoList[i]);

                let isReward = false;
                if(cfg.uid === uid && cfg.gamType === gameType){
                    let dwLv = cfg.dwLv;
                    let dwType = cfg.dwType === 0 ? 1 : cfg.dwType;//默认段位等级就是1
                    //该玩家赢了
                    if(isWin === 1){
                        log.warn(`===用户 ${cfg.name} 赢了===`);
                        cfg.dwXzNum += 1;
                        cfg.xzNumCost += 1;
                        //判断是否可以晋级
                        let cfgZt = gameZtCfg.dwlvCfg[dwType];
                        log.warn('===========判断是否可以晋级============',cfg.dwXzNum ,cfgZt.costXz)
                        if(cfg.dwXzNum >= cfgZt.costXz){
                            if(dwLv + 1 >= cfgZt.lvMin && dwLv + 1 <= cfgZt.lvMax){ //单纯的晋级不晋段位
                                log.warn('=========单纯的晋级不晋段位=======')
                                cfg.dwLv++;
                                cfg.dwXzNum = cfg.dwXzNum - cfgZt.costXz;
                                isReward = true;
                                await redisBase.updateGameListTzValue(i,JSON.stringify(cfg));
                            }else {
                                //晋级且晋段位      //这个使用需要给段位结算
                                cfgZt = gameZtCfg.dwlvCfg[dwType+1];
                                log.warn('=========晋级且晋段位=======',cfg.dwXzNum,cfgZt.costXz);
                                if(cfg.dwXzNum >= cfgZt.costXz){
                                    cfg.dwLv++;
                                    cfg.dwXzNum = cfg.dwXzNum - cfgZt.costXz;
                                    isReward = true;
                                    await redisBase.updateGameListTzValue(i,JSON.stringify(cfg));
                                }else{
                                    log.warn('=========晋级且晋段位勋章不够=======')
                                }
                            }
                        }

                        if(isReward === true){
                            log.error('========有段位奖励=========')
                            log.error('=========updateDwLv1===========',cfg.xzNumCost);
                            let res =  AlgorZt.updateDwLv(cfg.xzNumCost);
                            log.error('=========updateDwLv2===========',res);

                            cfg.dwLv = res.lv;
                            cfg.dwType = res.dwType;

                            let cli = null;
                            for (let j = 0; j < session.length; j++) {
                                if(cfg.uid === session[j].uid){
                                    cli = session[j].client;
                                    break;
                                }
                            }

                            setTimeout(()=>{
                                this.broadDwGameEnd(cfg.roomId,res,cli);
                            },500)
                        }
                        await redisBase.updateGameListTzValue(i,JSON.stringify(cfg));
                    }else if(isWin === 0){//该玩家输了
                        log.warn(`===用户 ${cfg.name} 输了===`);
                        if(cfg.dwXzNum > 0){
                            cfg.dwXzNum -= 1;
                        }
                        if(cfg.xzNumCost > 0) {
                            cfg.xzNumCost -= 1;
                        }
                    }


                    log.error('=========updateDwLv3===========');

                    break;
                }
            }
        }
    }

    //段位结算
    // lv: 0,
    //     dwType: 0,
    //     reward: 0,
    async broadDwGameEnd(roomId, cfg,client){
        log.info('==========broadDwGameEnd============',roomId,cfg);
        let ret = {
            type: CmdZt.ThemeMatchGameLvUpEndBroadcast,
            data:{
                rewardType:cfg.rdType,
                rewardNum: cfg.reward,
                dwLv:cfg.lv,
                dwType:cfg.dwType,
                gameType: 1, // 主题赛1 每日挑战赛2 好有pk赛3
            }
        }
        let roomInfo = await global.gameSerMgr.gameRedis.get_redis_in_room_list_zt_by_roomid(roomId);
        ret.data.gameType = roomInfo.gameTypeZt;
        log.info('==========broadDwGameEnd==end==========',ret);
        client.send(JSON.stringify(ret));
    }

}

module.exports = GameZtEnd.getInstance();